package com.qd.core.service;

import com.qd.common.sys.domain.entity.login.LoginUserDTO;
import com.qd.common.sys.domain.entity.meun.MenuDTO;
import com.qd.system.service.menu.MenuHoldService;
import com.qd.system.service.person.PersonRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户权限处理
 *
 * @author sjk
 */
@Component
@RequiredArgsConstructor
public class SysPermissionService {
    private final PersonRoleService personRoleService;
    private final MenuHoldService menuHoldService;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(LoginUserDTO user) {
        final Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
        } else {
            roles.addAll(personRoleService.getRoleCodeByPersonId(user.getPersonId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(LoginUserDTO user) {
        Set<String> perms;
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms = new HashSet<>(1);
            perms.add("*:*:*");
        } else {
            final List<MenuDTO> menuList = menuHoldService.getMenuList(user.getPersonId());
            if (menuList.isEmpty()) {
                perms = Collections.emptySet();
            } else {
                perms = menuList.stream().map(MenuDTO::getPerms).filter(StringUtils::hasLength).collect(Collectors.toSet());
            }
        }
        return perms;
    }
}
